package mapper;

import server.HttpServlet;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yutao
 * @create 2020-05-31 9:57
 **/
public class Mapper {

    private MappedHost mappedHost;

    public synchronized static Mapper instance() {
        return new Mapper();
    }

    public synchronized void add(String host, String port, String projectName, String projectPath, String webxmlPath, String classPath, String key, HttpServlet httpServlet) {
        if (this.mappedHost != null && mappedHost.getHost().equals(host)) {
            List<MappedContext> mappedContextList = this.mappedHost.getMappedContextList();
            if (!mappedContextList.isEmpty()) {
                for (MappedContext mappedContext : mappedContextList) {
                    // 是否有相同的 projectName
                    if (mappedContext.getProjectName().equals(projectName)) {
                        MappedWrapper mappedWrapper = new MappedWrapper(key, httpServlet);
                        mappedContext.getWrapperList().add(mappedWrapper);
                        return;
                    }
                }
            }
            MappedWrapper mappedWrapper = new MappedWrapper(key, httpServlet);
            List<MappedWrapper> mappedWrapperList = new ArrayList<>();
            mappedWrapperList.add(mappedWrapper);
            MappedContext mappedContext = new MappedContext(projectName, projectPath, webxmlPath, classPath, mappedWrapperList);
            this.mappedHost.getMappedContextList().add(mappedContext);
        } else {
            MappedWrapper mappedWrapper = new MappedWrapper(key, httpServlet);
            List<MappedWrapper> mappedWrapperList = new ArrayList<>();
            mappedWrapperList.add(mappedWrapper);
            MappedContext mappedContext = new MappedContext(projectName, projectPath, webxmlPath, classPath, mappedWrapperList);
            List<MappedContext> mappedContexts = new ArrayList<>();
            mappedContexts.add(mappedContext);
            this.mappedHost = new MappedHost(host, port, mappedContexts);
        }
    }

    public MappedHost getMappedHost() {
        return mappedHost;
    }
}
